package com.zpdhy.summer.service.impl;

import com.jcraft.jsch.ChannelSftp;
import com.zpdhy.summer.service.Message;
import com.zpdhy.summer.service.SftpService;
import com.zpdhy.summer.sftp.SFTPChannel;
import com.zpdhy.summer.sftp.SFTPConstants;

import java.io.File;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * Created by kedong on 2017/11/18 0018.
 */
public class SftpServiceImpl implements SftpService {

    private final Message message;
    private final DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    public SftpServiceImpl(Message message) {
        this.message = message;
    }


    @Override
    public void uploadFile() {
        try {
            SFTPChannel sftpChannel = new SFTPChannel();

            Map<String, String> sftpDetails = new HashMap<>();
            // 设置主机ip，端口，用户名，密码
            sftpDetails.put(SFTPConstants.SFTP_REQ_HOST, "192.168.31.106");
            sftpDetails.put(SFTPConstants.SFTP_REQ_USERNAME, "root");
            sftpDetails.put(SFTPConstants.SFTP_REQ_PASSWORD, "kedong");
            sftpDetails.put(SFTPConstants.SFTP_REQ_PORT, "22");
            String baseDir = "E:\\home\\Projects\\IdeaProjects\\Kairui\\";
            List<String> list = new ArrayList<>();
            Map<String, String> filenameMap = new HashMap<>();
            String[] strs = new String[]{"Kairui_System", "Kairui_Service", "Kairui_RestApi"};
            String dir;
            File file;
            for (int i = 0; i < 3; i++) {
                dir = baseDir + strs[i] + "\\target";
                file = new File(dir);
                String[] filenames = file.list();
                for (String filename : filenames != null ? filenames : new String[0]) {
                    if (filename.endsWith(".war")) {
                        String name = dir + "\\" + filename;
                        list.add(name);
                        filenameMap.put(name, filename);
                    }
                }
            }

            if (list.size() > 0) {
                String dst = "/home/zpdhy/tmp/"; // 目标文件名
                for (String src : list) {
                    ChannelSftp sftp = sftpChannel.getChannel(sftpDetails, 60000);
                    sftp.put(src, dst + filenameMap.get(src), ChannelSftp.OVERWRITE);
                    sftp.quit();
                }
                sftpChannel.closeChannel();

                message.appendStringToTextArea(dateFormat.format(new Date()) + "：finished...\n");

            }

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
